const app = getApp()
const middleware = require('../../utils/middleware.js')
import regeneratorRuntime from '../../lib/wxPromise.min.js'
import * as API_Trade from '../../api/trade'
import * as API_Order from '../../api/order'
import * as API_Wechat from '../../api/wechat'
import { Foundation } from '../../ui-utils/index'

Page(middleware.identityFilter({
    data: {
      trade_sn: '',
      order_sn: '',
      // 支付方式
      payment: '',
      // 订单详情
      order: '',
      //订单状态
      order_status:'',
      // 显示确认订单完成支付dialog
      showConfirmDialog: false,
      // 支付按钮禁用
      disabledPay: true,
      // 倒计时
      timer: null,
      day: 0,
      hours: '00',
      minutes: '00',
      seconds: '00',
      // 是否需要调起支付
      needPay: true
    },
    async onLoad(options) {
      this.setData({
        order_sn: options.order_sn || '',
        trade_sn: options.trade_sn || ''
      });
      const responses = await Promise.all([
        this.data.trade_sn
          ? API_Trade.getCashierData({ trade_sn: this.data.trade_sn })
          : API_Trade.getCashierData({ order_sn: this.data.order_sn }),
        API_Trade.getPaymentList('WAP')
      ]);
      let orderMsg = responses[0];
      let _needPay = orderMsg.need_pay_price;
      this.contDown(orderMsg.pay_time_left);
      orderMsg.order_create_time = Foundation.unixToDate(orderMsg.order_create_time);
      this.setData({
        order: {
          ...orderMsg,
          need_pay_price: Foundation.formatPrice(_needPay)
        },
        needPay: _needPay !== 0,
        payment: responses[1][1]
      });
      this.initiatePay();
    },
    onShow() {
    },
    /** 发起支付 */
    async initiatePay() {
      wx.showLoading({ title: '准备支付...' });
      const that = this;
      that.setData({
        disabledPay: true
      });
      const trade_type = this.data.trade_sn ? 'trade' : 'order';
      const sn = this.data.trade_sn || this.data.order_sn;
      const client_type = 'MINI';
      const payment_plugin_id = this.data.payment.plugin_id;
      const { goods_image, good_num, order_sn, order_type } = that.data.order;
      API_Trade.initiatePay(trade_type, sn, {
        client_type,
        pay_mode: 'normal',
        payment_plugin_id
      }).then(async response => {
        wx.hideLoading();
        console.log(that.data.order);
        if (!that.data.needPay) {
          setTimeout(() => {
            wx.redirectTo({ url: `/pages/pay/pay-result?img=${goods_image}&num=${good_num}&order_sn=${order_sn}&type=${order_type}` });
          }, 1000);
          return;
        };
        // 获取订阅消息id
        let _params = {
          types: 'SHIP_NOTICE,CANCEL_NOTICE_1,REFUND_NOTICE'
        };
        let _tpls = await API_Wechat.getNoticeTpl(_params);
        const params = {};
        response.form_items.forEach(item => {
          params[item.item_name] = item.item_value;
        });
        // 调起微信支付
        wx.requestPayment({
          ...params,
          success: function (res) {
            // 调用消息订阅提示[SHIP_NOTICE：订单发货提醒；CANCEL_NOTICE_1：订单取消通知；REFUND_NOTICE：多退少补通知]
            wx.requestSubscribeMessage({
              tmplIds: _tpls,
              complete(res) {
                console.log(response)
              }
            });
            that.setData({
              disabledPay: true
            });
            wx.redirectTo({ url: `/pages/pay/pay-result?img=${goods_image}&num=${good_num}&order_sn=${order_sn}&type=${order_type}` });
          },
          fail: function (error) {
            if (error.errMsg === 'requestPayment:fail cancel') {
              wx.showModal({
                title: '支付提示',
                content: '订单支付失败，请重新支付',
                confirmText: '重新支付',
                cancelText: '稍后在说',
                confirmColor: '#e50c0c',
                cancelColor: '#cdcdcd',
                success(res) {
                  if (res.confirm) {
                    that.initiatePay();
                  } else if (res.cancel) {
                    that.setData({
                      disabledPay: false
                    });
                    // 调用消息订阅提示[PAY_NOTICE：待付款提醒；CANCEL_NOTICE_1：订单取消通知]
                    app.sendNotice('PAY_NOTICE,CANCEL_NOTICE_1');
                    console.log('用户点击取消');
                  };
                }
              });
            } else {
              that.setData({
                disabledPay: false
              });
            }
          }
        });
      }).catch(() => {
        wx.hideLoading();
      });
    },
    /** 倒计时 */
    contDown(times){
      let end_time = times
      this.setData({
        timer:setInterval(()=>{
          if(end_time<=0){
            clearInterval(this.data.timer)
            this.triggerEvent('count-end')
          }else{
            const time = Foundation.countTimeDown(end_time)
            this.setData({
              day : parseInt(time.day),
              hours : time.hours,
              minutes : time.minutes,
              seconds : time.seconds
            })
            end_time --
          }
        },1000)
      })
    }
  })
)